package com.example.cyk.controller;


import com.example.cyk.config.response.AppReturn;
import com.example.cyk.config.response.CodeMsg;
import com.example.cyk.model.User;
import com.example.cyk.model.Userinfo;
import com.example.cyk.model.vo.UserVO;
import com.example.cyk.service.IUserService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @RequestMapping("/login")
    public AppReturn login(@RequestBody @NonNull User user) {
        //1.非空校验
        if(!StringUtils.hasLength(user.getUsername()) ||
                !StringUtils.hasLength(user.getPassword())) {
            log.warn(CodeMsg.ERROR_PARAM.toString());
            return AppReturn.fail(CodeMsg.ERROR_PARAM);
        }
        UserVO userVO = userService.login(user.getUsername(), user.getPassword());
        log.info("用户上线: " + user.getUsername());
        return AppReturn.success(CodeMsg.SUCCESS, userVO);
    }

    @RequestMapping("/logout")
    public AppReturn logout(@RequestParam("username") @NonNull String username) {
        userService.logout(username);
        log.info("用户下线: " + username);
        return AppReturn.success();
    }

    @RequestMapping("/reg")
    public AppReturn reg(@RequestBody @NonNull UserVO user) {
        //1.非空校验
        if(!StringUtils.hasLength(user.getUsername()) || !StringUtils.hasLength(user.getPassword()) ||
        !StringUtils.hasLength(user.getNickname())) {
            return AppReturn.fail(CodeMsg.ERROR_PARAM);
        }
        //2.注册服务
        userService.reg(user);
        return AppReturn.success();
    }

    @GetMapping("/info")
    public AppReturn info(@NonNull Long userId) {
        //1.获取用户信息服务
        Userinfo userinfo = userService.getUserinfo(userId);
        return AppReturn.success(userinfo);
    }

}
